package ch02.test;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;
import java.io.IOException;

public class text6 {
    public static void main(String[] args) throws TransformerException, ParserConfigurationException, IOException, SAXException {
        //得到DOM解析器的工厂实例
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        //从DOm工厂获取DOM解析器
        DocumentBuilder db = dbf.newDocumentBuilder();
        //解析XMl文档，得到一个Document对象。即DOM树
        Document doc = db.parse("src/ch02/entity/demo2.xml");
        //找到删除的节点
        NodeList list = doc.getElementsByTagName("Brand");
        for (int i=0;i<list.getLength();i++){
            Element brandElement =(Element)list.item(i);
            String brandName = brandElement.getAttribute("name");
            if (brandName.equals("SAMSUNG")){
               brandElement.getParentNode().removeChild(brandElement);

            }
        }

        //保存XMl文件
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource domSource = new DOMSource(doc);
        transformer.setOutputProperty(OutputKeys.ENCODING, "gb2312");
        StreamResult result = new StreamResult(
                new FileOutputStream("src/ch02/entity/demo2.xml")
        );
        //把DOm树转换为XMl文件
        transformer.transform(domSource,result);
    }
}


